<template>
    <div :class="['knowledgeTree',{'treeLine':isShowLine}]">
        <el-scrollbar style="height: 100%">
            <el-tree :data="data" node-key="id" :current-node-key="currentId" default-expand-all :indent="isShowLine?0:10"
                     ref="knowledgeTree" :expand-on-click-node="false" highlight-current @node-click="nodeClick"
                     :draggable="canEdit && type =='class'" :allow-drag="allowDrag" :allow-drop="allowDrop" @node-drop="nodeDrop">
                <span class="custom-tree-node" slot-scope="{ node, data }" @mouseenter="mouseenter(data)" @mouseleave="mouseleave(data)">
                    <span :title="node.label" class="title">{{ node.label }}</span>
                    <span v-if="node.level != 4">
                        <el-tooltip effect="light" content="添加" placement="top" :enterable="false">
                            <span class="iconfont icon-tianjia1" v-show="data.show" @click.stop="() => appendTree(node, data)"></span>
                        </el-tooltip>
                    </span>
                    <span v-if="data.id != 0">
                        <el-tooltip effect="light" content="编辑" placement="top" :enterable="false">
                            <span class="iconfont icon-bianji" v-show="data.show" @click.stop="() => editTree(node, data)"></span>
                        </el-tooltip>
                        <el-tooltip effect="light" content="删除" placement="top" :enterable="false">
                            <span class="iconfont icon-shanchu" v-show="data.show" @click.stop="() => removeTree(node, data)"></span>
                        </el-tooltip>
                    </span>
                </span>
            </el-tree>
        </el-scrollbar>

        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="480px">
            <div class="addEditTree">
                <span>分类名称</span>
                <el-input v-model="className" placeholder="请输入分类名称" maxlength="8" size="small"></el-input>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false" size="small" type="text">取 消</el-button>
                <el-button type="primary" @click="submit" size="small">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { getClassList, addClass, editClass, delClass, orderClass } from "@/api/knowledge.js";
import { generateOptions } from "@/utils/validate";
import { mapGetters } from "vuex";
export default {
    name: "knowledgeTree",
    props: {
        canEdit: {
            type: Boolean,
            default: true
        },

        optionList: {
            type: Array,
            default: () => []
        },
        name: {
            type: String,
            default: "全集类目"
        },
        type: {
            type: String
        },
        isShowLine: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            data: [
                {
                    id: "0",
                    label: this.name,
                    children: [],
                },
            ],
            classList: [],
            className: "",
            classId: null,
            currentId: "0",
            dialogVisible: false,
            dialogType: "add",
            maxLevel: 0
        };
    },
    created() {
        this.getClassList(false);
    },
    mounted() {
        if (this.type == "class") {
            this.data[0].children = this.knowledgeList;
        } else if (this.type == "material") {
            this.data[0].children = this.materialList;
        }
        this.$emit('update:optionList', this.data[0].children);
    },
    methods: {
        //获取分类
        getClassList(isUpdate = true) {
            if ((this.type == "class" || this.type == "material") && !isUpdate) {
                return;
            }
            var url = `/v1/admin/${this.type}/getClassList`;
            getClassList(url).then((resp) => {
                if (resp.status == 0) {
                    this.classList = resp.data.list || [];
                    var json = JSON.stringify(generateOptions(this.classList));
                    json = json.replace(/className/g, "label");
                    this.data[0].children = JSON.parse(json);
                    this.$emit('update:optionList', JSON.parse(json));
                    if (this.type == "class") {
                        this.$store.dispatch("knowledge/setArrayList", { knowledgeList: JSON.parse(json) });
                    } else if (this.type == "material") {
                        this.$store.dispatch("knowledge/setArrayList", { materialList: JSON.parse(json) });
                    }
                }
            });
        },
        //添加分类
        appendTree(node, data) {
            this.className = "";
            this.classId = data.id;
            this.dialogType = "add";
            this.dialogVisible = true;
        },
        //编辑分类
        editTree(node, data) {
            console.log(data);
            this.className = data.label;
            this.classId = data.id;
            this.dialogType = "edit";
            this.dialogVisible = true;
        },
        //删除分类
        removeTree(node, data) {
            this.$confirm("是否确定删除?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                var url = `/v1/admin/${this.type}/delClassById`;
                delClass(url, { id: data.id }).then((resp) => {
                    if (resp.status == 0) {
                        this.currentId = "0";
                        this.getClassList();
                        this.$antMessage.success("删除成功");
                    } else {
                        this.$antMessage.warning(resp.message);
                    }
                });
            }).catch();
        },
        submit() {
            if (!this.className) {
                this.$antMessage.warning("请输入分类名称");
                return;
            }
            var param = {
                className: this.className,
            };
            if (this.dialogType == "add") {
                var url = `/v1/admin/${this.type}/addClass`;
                param.parentId = this.classId;
                addClass(url, param).then((resp) => {
                    if (resp.status == 0) {
                        this.getClassList();
                        this.$antMessage.success("添加成功");
                    } else {
                        this.$antMessage.warning(resp.message);
                    }
                });
            } else {
                const arr = this.classList.find((d) => d.id === this.classId);
                param.id = this.classId;
                param.orderId = arr.orderId;
                param.status = arr.status;
                var url = `/v1/admin/${this.type}/editClass`;
                editClass(url, param).then((resp) => {
                    if (resp.status == 0) {
                        this.getClassList();
                        this.$antMessage.success("编辑成功");
                    } else {
                        this.$antMessage.warning(resp.message);
                    }
                });
            }
            this.dialogVisible = false;
        },
        nodeClick(data, node) {
            // if (node.isLeaf) {
            //     this.currentId = data.id;
            //     this.$emit("getClassId", data.id);
            // } else {
            //     node.isCurrent = false;
            //     this.$refs.knowledgeTree.setCurrentKey(this.currentId)
            // }
            this.currentId = data.id;
            this.$emit("getClassId", data.id);
        },
        mouseenter(data) {
            if (this.canEdit) {
                this.$set(data, "show", true);
            }
        },
        mouseleave(data) {
            this.$set(data, "show", false);
        },
        allowDrag(draggingNode, dropNode, type) {
            if (draggingNode.level == 1) {
                return false;
            } else {
                return true;
            }
        },
        allowDrop(draggingNode, dropNode, dropType, ev) {
            this.countNodeLevel(draggingNode);
            let deep = this.maxLevel - draggingNode.level + 1;
            this.maxLevel = 0;
            if (dropType == "inner") {
                let isDrag = deep + dropNode.level <= 4;
                return isDrag;
            } else {
                let isDrag = deep + dropNode.parent.level <= 4;
                return isDrag;
            }

        },
        countNodeLevel(node) {
            if (node.childNodes != null && node.childNodes.length > 0) {
                for (let i = 0; i < node.childNodes.length; i++) {
                    if (node.childNodes[i].level > this.maxLevel) {
                        this.maxLevel = node.childNodes[i].level;
                    }
                    this.countNodeLevel(node.childNodes[i]);
                }
            } else {
                this.maxLevel = node.level;
            }
        },
        nodeDrop(draggingNode, dropNode, dropType, ev) {
            var classList = JSON.stringify(this.data[0].children);
            classList = JSON.parse(classList.replace(/label/g, "className"));
            var url = `/v1/admin/${this.type}/orderClass`;
            orderClass(url, { classList }).then(resp => {
                if (resp.status == 0) {
                    this.getClassList();
                    this.$antMessage.success("编辑成功");
                } else {
                    this.$antMessage.warning(resp.message);
                }
            });
        }
    },
    computed: {
        ...mapGetters(["knowledgeList", "materialList"]),
        dialogTitle() {
            return this.dialogType == "add" ? "添加分类" : "编辑分类";
        },
    },
    watch: {
        knowledgeList(val) {
            if (this.type == "class") {
                this.data[0].children = val;
                this.$emit('update:optionList', this.data[0].children);
            }
        },
        materialList(val) {
            if (this.type == "material") {
                this.data[0].children = val;
                this.$emit('update:optionList', this.data[0].children);
            }
        },
    }
};
</script>

<style lang="scss">
.knowledgeTree {
    height: 100%;
    // background: #f5fbff;
    flex-shrink: 0;
    .header {
        height: 45px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 15px;
    }
    .info {
        padding-left: 15px;
        font-size: 12px;
        color: #999;
        margin-bottom: 5px;
    }
    .custom-tree-node {
        display: flex;
        align-items: center;
        .title {
            margin-right: 10px;
            max-width: 110px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            display: inline-block;
            color: #676e75;
            font-size: 14px;
        }
        .iconfont {
            color: #b7c1c9;
            font-size: 20px;
            margin-right: 10px;
            &:hover {
                color: #abb4bc;
            }
        }
    }
    .addEditTree {
        margin-top: 30px;
        display: flex;
        align-items: center;
        > span {
            flex-shrink: 0;
            margin-right: 20px;
        }
    }
    .el-tree-node__expand-icon {
        font-size: 16px;
    }
    .el-tree-node__content {
        height: 34px;
    }
    .el-tree--highlight-current
        .el-tree-node.is-current
        > .el-tree-node__content {
        background: transparent;
        .custom-tree-node .title {
            color: #6b5ee2;
        }
    }
}
</style>

<style lang="scss" scoped>
</style>